package com.cyl.h5.service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.oms.domain.entity.Order;
import com.cyl.manager.oms.domain.entity.OrderItem;
import com.cyl.manager.oms.mapper.OrderItemMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.config.LocalDataUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.cyl.manager.oms.mapper.PmsAppraiseMapper;
import com.cyl.h5.domain.entity.PmsAppraise;
import com.cyl.h5.domain.query.PmsAppraiseQuery;

/**
 * 商品评价表Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class PmsAppraiseService {
    @Autowired
    private PmsAppraiseMapper pmsAppraiseMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 查询商品评价表
     *
     * @param id 商品评价表主键
     * @return 商品评价表
     */
    public PmsAppraise selectById(Integer id) {
        return pmsAppraiseMapper.selectById(id);
    }

    /**
     * 查询商品评价表列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 商品评价表
     */
    public List<PmsAppraise> selectList(PmsAppraiseQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<PmsAppraise> qw = new QueryWrapper<>();
        Long orderId = query.getOrderId();
        if (orderId != null) {
            qw.eq("order_id", orderId);
        }
        Long userId = query.getUserId();
        if (userId != null) {
            qw.eq("user_id", userId);
        }
        String statusSatisfact = query.getStatusSatisfact();
        if (!StringUtils.isEmpty(statusSatisfact)) {
            qw.eq("status_satisfact", statusSatisfact);
        }
        return pmsAppraiseMapper.selectList(qw);
    }

    /**
     * 新增商品评价表
     *
     * @param pmsAppraise 商品评价表
     * @return 结果
     */
    public int insert(PmsAppraise pmsAppraise) {
        if (pmsAppraise.getOrderId() != null) {
            //查询当前订单 获取商品信息
            Order order = orderMapper.selectById(pmsAppraise.getOrderId());
            order.setStatus(6);
            orderMapper.updateById(order);
        }
        UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        pmsAppraise.setUserId(member.getId());
        pmsAppraise.setUserName(member.getName());
        pmsAppraise.setUserImage(member.getImage());
        pmsAppraise.setCreateTime(LocalDateTime.now());
        return pmsAppraiseMapper.insert(pmsAppraise);
    }

    /**
     * 修改商品评价表
     *
     * @param pmsAppraise 商品评价表
     * @return 结果
     */
    public int update(PmsAppraise pmsAppraise) {
        return pmsAppraiseMapper.updateById(pmsAppraise);
    }

    /**
     * 批量删除商品评价表
     *
     * @param ids 需要删除的商品评价表主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
        return pmsAppraiseMapper.updateDelFlagByIds(ids);
    }

    /**
     * 删除商品评价表信息
     *
     * @param id 商品评价表主键
     * @return 结果
     */
    public int deleteById(Long id) {
        Long[] ids = {id};
        return pmsAppraiseMapper.updateDelFlagByIds(ids);
    }


    public List<PmsAppraise> goodAppraise(PmsAppraiseQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        // 1. 根据商品ID查询所有关联的订单项
        List<OrderItem> orderItems = orderItemMapper.selectProduct(query.getProductId());

        if (CollectionUtils.isEmpty(orderItems)) {
            return Collections.emptyList();
        }

        // 2. 收集所有订单ID
        List<Long> orderIds = orderItems.stream()
                .map(OrderItem::getOrderId)
                .collect(Collectors.toList());

        // 3. 查询评价信息
        List<PmsAppraise> appraises = pmsAppraiseMapper.goodAppraise(orderIds,query.getLabelList(), query.getStatus());

        // 4. 构建 orderId -> spData 的映射
        Map<Long, List<Map<String, String>>> spDataMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();

        for (OrderItem item : orderItems) {
            String spData = item.getSpData();
            if (StringUtils.isNotBlank(spData)) {
                try {
                    // 解析 JSON 字符串成 Map<String, String>
                    Map<String, String> spDataMapTemp = objectMapper.readValue(
                            spData,
                            new TypeReference<Map<String, String>>() {}
                    );

                    // 转换为 List<Map<String, String>>
                    List<Map<String, String>> skuSpecList = spDataMapTemp.entrySet().stream()
                            .map(entry -> {
                                Map<String, String> specEntry = new HashMap<>();
                                specEntry.put("key", entry.getKey());
                                specEntry.put("value", entry.getValue());
                                return specEntry;
                            })
                            .collect(Collectors.toList());

                    spDataMap.put(item.getOrderId(), skuSpecList);
                } catch (Exception e) {
                    spDataMap.put(item.getOrderId(), Collections.emptyList()); // 解析失败设为空列表
                }
            } else {
                spDataMap.put(item.getOrderId(), Collections.emptyList());
            }
        }

        // 5. 将 spData 塞入对应的 PmsAppraise 对象中
        for (PmsAppraise appraise : appraises) {
            List<Map<String, String>> skuList = spDataMap.getOrDefault(appraise.getOrderId(), Collections.emptyList());
            appraise.setSkuList(skuList);
        }

        return appraises;
    }

    public List<Map<String, Object>> appraiseCount(PmsAppraiseQuery query) {
        // 1. 根据商品ID查询所有关联的订单项
        List<OrderItem> orderItems = orderItemMapper.selectProduct(query.getProductId());
        List<Map<String, Object>> mapList = new ArrayList<>();
        if ( orderItems.size() == 0){
            return mapList;
        }
        // 2. 收集所有订单ID
        List<Long> orderIds = orderItems.stream()
                .map(OrderItem::getOrderId)
                .collect(Collectors.toList());

        List<Map<String, Object>> list = pmsAppraiseMapper.appraiseCount(orderIds);
        if (list == null || list.size()==0){
            return mapList;
        }

        return pmsAppraiseMapper.appraiseCount(orderIds);

    }
}
